package com.entrogy.controller;

import com.entrogy.bean.*;
import com.entrogy.service.PermissionService;
import com.entrogy.service.RoleService;
import com.entrogy.service.UserService;
import com.entrogy.utils.constants.ErrorEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色的编辑控制器
 * @author luoxingjiang
 * @date 2019-1
 */
@RestController
@RequestMapping("/role")
@Api(description = "角色操作接口")
public class RoleController {

	private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

	@Autowired
	private RoleService roleService;

	@Autowired
	private UserService userService;

	@Autowired
	private PermissionService permissionService;

	@RequestMapping(value = "/findAllRoles",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "roleName", value = "角色名", dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "schoolCode", value = "学校ID", dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "currentPage", value = "当前页", dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页条", dataType = "Integer", paramType = "query"),
	})
//	@RequiresPermissions("role:list")
	public Msg findRoles(String roleName, Integer schoolCode, Integer currentPage, Integer pageSize) {
		if (currentPage == null || pageSize == null){
			currentPage = 0;
			pageSize = 0;
		}
		PageHelper.startPage(currentPage, pageSize);
		List<Role> roles = roleService.findRoles(roleName,schoolCode);
		PageInfo<Role> pageInfo = new PageInfo<>(roles);
		long totalCount = pageInfo.getTotal();
		return Msg.success().add("roles",roles).add("totalCount", totalCount);
	}

	/**
	 * 更新某个角色对应的权限
	 * @param updateRole
	 * @return
	 */
	@RequestMapping(value = "/updateRole",method = RequestMethod.POST)
//    @RequiresPermissions("role:update")
	public Msg updateRole(@ModelAttribute UpdateRoleEntity updateRole) {
		try{
			List<UpdateRoleEntity> updateRoles = new ArrayList<>();
			updateRoles.add(updateRole);
			roleService.updateRoles(updateRoles);
			return Msg.success();
		}catch (Exception e){
			e.printStackTrace();
			return Msg.fail(ErrorEnum.E_101,ErrorEnum.E_101.getErrorMsg());
		}

	}

	/**
	 * 批量弃用角色
	 * @param discardRoleId
	 * @return
	 */
	@RequestMapping(value = "/discardRole",method = RequestMethod.POST)
//    @RequiresPermissions("role:delete")
	public Msg discardRole(@RequestParam Integer discardRoleId) {
		List<Integer> discardRoleIds = new ArrayList<>();
		discardRoleIds.add(discardRoleId);
		if (discardRoleIds.size() > 0){
			try{
				roleService.discardRoleByIds(discardRoleIds);
				return Msg.success();
			}catch (Exception e){
				e.printStackTrace();
				return Msg.fail(ErrorEnum.E_101,ErrorEnum.E_100.getErrorMsg());
			}
		}
		return Msg.fail(ErrorEnum.E_101,"您尚未选中要弃用的角色!");
	}

	/**
	 * 批量启用角色
	 * @param enableRoleId
	 * @return
	 */
	@RequestMapping(value = "/enableRole",method = RequestMethod.POST)
	public Msg enableRole(@RequestParam Integer enableRoleId) {
		List<Integer> enableRoleIds = new ArrayList<>();
		enableRoleIds.add(enableRoleId);
		if (enableRoleIds.size() > 0){
			try{
				roleService.enableRoleByIds(enableRoleIds);
				return Msg.success();
			}catch (Exception e){
				e.printStackTrace();
				return Msg.fail(ErrorEnum.E_101,ErrorEnum.E_100.getErrorMsg());
			}
		}
		return Msg.fail(ErrorEnum.E_101,"您尚未选中要启用的角色!");
	}

	/**
	 * 查找出所有角色，用于下拉列表选择
	 * @param schoolCode
	 * @param selectSchoolCode
	 * @return
	 */
	@ApiOperation(value = "查找出所有角色，用于下拉列表选择")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "schoolCode", value = "学校ID", dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "selectSchoolCode", value = "要创建角色的学校ID", dataType = "Integer", paramType = "query")
	})
	@RequestMapping(value = "/findAllRolesSimple",method = RequestMethod.GET)
	public Msg findAllRolesSimple(Integer schoolCode, Integer selectSchoolCode) {
		List<Role> roles;
		//如果是超级管理员，则根据超级管理员要为哪所学校创建用户分配角色时，当选择的学校确定时，查询对应学校的角色
		if (schoolCode==1 || schoolCode.equals("1")){
			roles=roleService.findAllRolesSimple(selectSchoolCode);
		}else{
			roles = roleService.findAllRolesSimple(schoolCode);
		}
		return Msg.success().add("roles",roles);
	}

	@ApiOperation(value = "查找出所有角色，用于下拉列表选择---根据userId")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "uid", value = "用户id", dataType = "String", paramType = "query"),
	})
	@GetMapping(value = "/list-all-role")
	public Msg listAllRole(String uid) {
		Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		List<Role> roles = roleService.findAllRolesSimple(schoolCode);
		return Msg.success().add("roles",roles);
	}

	/**
	 * 新增角色
	 * @param addRole
	 * @return
	 */
	@RequestMapping(value = "/addRole",method = RequestMethod.POST)
//	@RequiresPermissions("role:add")
	public Msg addRole(@ModelAttribute AddRoleEntity addRole) {
		boolean result = roleService.addRole(addRole);
		if (result){
			return Msg.success();
		}else {
			return Msg.fail(ErrorEnum.E_101,"新增角色失败");
		}
	}

	/**
	 * 找出所有权限信息，用于新增角色时分配权限等功能
	 * @return
	 */
	@ApiImplicitParam(name = "schoolCode", value = "学校ID", dataType = "int", paramType = "query")
	@RequestMapping(value = "/findAllPermission",method = RequestMethod.GET)
	public Msg findAllPermission(Integer schoolCode) {
		List<PermissionAndMenu> permissionAndMenus = roleService.findAllPermission(schoolCode);
		return Msg.success().add("permissionAndMenus",permissionAndMenus);

	}

	@ApiOperation(value = "查询拥有教师审核权限的角色id，此接口用于当教师既是审核人员，又提交了审核时，查询该教师必选角色使用")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "uid", value = "用户id", dataType = "String", paramType = "query"),
	})
	@GetMapping(value = "/list-has-check-permission-role")
	public Msg listHasCheckPermissionRole(String uid) {
		String permissionCode = "teacher-register:audit";
		// 判断该uid是否有审核权限
		boolean hasAuthorization = permissionService.hasAuthorization(uid, permissionCode);
		List<Integer> hasCheckPermissionRole = new ArrayList<>();
		Integer schoolCode = userService.getSchoolCodeByUserId(uid);
		if (hasAuthorization){
			hasCheckPermissionRole = roleService.listHasSomePermissionRole(permissionCode, schoolCode);
		}
		return Msg.success().add("hasCheckPermissionRole",hasCheckPermissionRole);

	}

}
